import style from './LeftBox.module.less'
import {ApartmentOutlined, VideoCameraOutlined, ApiOutlined, DesktopOutlined, GlobalOutlined} from "@ant-design/icons";
import {Link, useHistory} from "react-router-dom";
import React, {useEffect, useRef, useState} from "react";
import {Button, Input, Switch, Menu} from 'antd'
import Icon from "antd/es/icon";

const {SubMenu} = Menu;
const peer = require('../../../components/peer')


const offer_pc = new window.RTCPeerConnection()
const answer_pc = new window.RTCPeerConnection()

export default function LeftBox() {
    const [remoteCode, setRemoteCode] = useState('')
    const [localCode, setLocalCode] = useState('')
    const [controlStatus, setControlStatus] = useState('')
    const [controlText, setControlText] = useState('')
    const [webSocketStatus, setWebSocketStatus] = useState(false)
    const [isExpand, setIsExpand] = useState(false)
    const history = useHistory()
    let offer_candidates = []
    let answer_candidates = []


    const menuItems = [
        {
            key: "1",
            icon: <ApartmentOutlined/>,
            label: "设备总览",
            path: "/localHome/DeviceManage"
        },
        {
            key: "2",
            icon: <GlobalOutlined/>,
            label: "WebRTC调试",
            path: "/localHome/WebRTCTest"
        },
        {
            key: "3",
            icon: <ApiOutlined/>,
            label: "WebSocket调试",
            path: "/localHome/WebSocketTest"
        },
        {
            key: "4",
            icon: <DesktopOutlined/>,
            label: "桌面流调试",
            path: "/localHome/DesktopTest"
        },
        {
            key: "5",
            icon: <VideoCameraOutlined/>,
            label: "摄像头调试",
            path: "/localHome/CameraTest"
        }
    ];

    useEffect(() => {
        // initOfferRTCPeerConnection()
        // initAnswerRTCPeerConnection()
        // openControlStateMonitor()
        // connectWebsocket()
        return () => {
            window.electronAPI.clearControlState()
            window.electronAPI.clearMasterCandidate()
            window.electronAPI.clearSlaveCandidate()
        };
    }, []);

    const gotoHome = () => {
        history.push('/home');
    };
    const toggleSize = () => {
        setIsExpand(!isExpand)
    }

    const connectWebsocket = async () => {
        if (!localCode) {
            let data = await window.electronAPI.login()
            setLocalCode(data.data.code)
            setRemoteCode(data.remoteCode)
            setWebSocketStatus('已开启')
        } else {
            await window.electronAPI.logout()
            setLocalCode('')
            setRemoteCode('')
            setWebSocketStatus('已关闭')
        }
    }


    const connectDevice = async () => {
        await window.electronAPI.getControl(JSON.stringify({
            remoteCode: remoteCode,
            event: 'control'
        }))
    }


    const openControlStateMonitor = () => {
        window.electronAPI.controlState((event, remoteCode, type) => {
            localStorage.setItem('remoteCode', remoteCode)
            if (type === 1) {
                setWebSocketStatus('正在远程控制')
                setRemoteCode(remoteCode)
            } else if (type === 2) {
                setWebSocketStatus('被远程控制中')
            }
        });
    }


    const createOffer = async () => {
        let offer = await offer_pc.createOffer({
            offerToReceiveAudio: false,
            offerToReceiveVideo: true
        })
        await offer_pc.setLocalDescription(offer)
        return offer_pc.localDescription
    }

    const sendOffer = async () => {
        try {
            const offer = await createOffer();
            console.log('offer.sdp:', offer.sdp)
            const finalData = JSON.stringify({
                event: 'forward',
                remoteCode: remoteCode,
                data: {
                    event: 'offer',
                    type: offer.type,
                    sdp: offer.sdp
                }
            })
            window.electronAPI.getForward(finalData);
        } catch (error) {
            console.error('Error sending offer:', error);
        }
    };


    const openGetOfferCandidateMonitor = () => {
        window.electronAPI.getSlaveCandidate((e, candidate) => {
            console.log('接收到slave-candidate')
            addOfferIceCandidate(candidate).then(r => {
            })
        })
    }
    const openGetAnswerCandidateMonitor = () => {
        window.electronAPI.getMasterCandidate((e, candidate) => {
            console.log('接收到master-candidate')
            addAnswerIceCandidate(candidate).then(r => {
            })
        })
    }

    async function addAnswerIceCandidate(data) {
        let candidate;
        if (data && data.data && data.data.candidate && data.data.candidate.candidate) {
            candidate = data.data.candidate.candidate;
        } else {
            candidate = null;
        }
        if (!candidate || !candidate.type) return
        answer_candidates.push(candidate)
        if (answer_pc.remoteDescription && answer_pc.remoteDescription.type) {
            for (let i = 0; i < answer_candidates.length; i++) {
                await answer_pc.addIceCandidate(new RTCIceCandidate(answer_candidates[i]))
            }
        }
    }

    async function addOfferIceCandidate(data) {
        let candidate;
        if (data && data.data && data.data.candidate && data.data.candidate.candidate) {
            candidate = data.data.candidate.candidate;
        } else {
            candidate = null;
        }
        if (!candidate || !candidate.type) return
        offer_candidates.push(candidate)
        if (offer_pc.remoteDescription && offer_pc.remoteDescription.type) {
            for (let i = 0; i < offer_candidates.length; i++) {
                await offer_pc.addIceCandidate(new RTCIceCandidate(offer_candidates[i]))
            }
            offer_candidates = []
        }
    }


    async function getScreenStream() {
        try {
            return await navigator.mediaDevices.getUserMedia({
                audio: false,
                video: {
                    mandatory: {
                        chromeMediaSource: 'desktop',
                        chromeMediaSourceId: 'screen:0:0'
                    }
                }
            });
        } catch (e) {
            console.log(e)
        }
    }


    async function createAnswer(sdp) {
        try {
            let stream = await getScreenStream();
            if (!stream) {
                throw new Error('Failed to get screen stream');
            }
            stream.getTracks().forEach(track => {
                answer_pc.addTrack(track, stream);
            });
            await answer_pc.setRemoteDescription({type: 'offer', sdp: sdp});
            await answer_pc.setLocalDescription(await answer_pc.createAnswer());
            return answer_pc.localDescription;
        } catch (error) {
            console.error('Error creating answer:', error);
            throw error;
        }
    }


    const openOfferMonitor = () => {
        window.electronAPI.getOffer((event, sdp) => {
            createAnswer(sdp).then((data) => {
                const finalData = JSON.stringify({
                    event: 'forward',
                    remoteCode: localStorage.getItem('remoteCode'),
                    data: {
                        event: 'answer',
                        sdp: data.sdp
                    }
                })
                window.electronAPI.getForward(finalData)
            })
        });
    }


    const openAnswerMonitor = () => {
        window.electronAPI.getAnswer(async (event, answer) => {
            console.log('answer.sdp', answer)
            await offer_pc.setRemoteDescription({type: 'answer', sdp: answer})
        })
    }


    const initAnswerRTCPeerConnection = async () => {
        answer_pc.onicecandidate = (e) => {
            const finalData = JSON.stringify({
                event: 'forward',
                remoteCode: localStorage.getItem('remoteCode'),
                data: {
                    event: 'slave-candidate',
                    candidate: e.candidate
                }
            })
            window.electronAPI.getForward(finalData)
        }
        await openOfferMonitor()
        await openGetAnswerCandidateMonitor()
    }


    const initOfferRTCPeerConnection = async () => {
        offer_pc.onicecandidate = (e) => {
            const finalData = JSON.stringify({
                event: 'forward',
                remoteCode: localStorage.getItem('remoteCode'),
                data: {
                    event: 'master-candidate',
                    candidate: e.candidate
                }
            })
            window.electronAPI.getForward(finalData)
        }

        offer_pc.onaddstream = (e) => {
            peer.emit('add-stream', e.stream)
        }
        await openGetOfferCandidateMonitor()
        await openAnswerMonitor()
    }


    return (
        <div className={style.leftContainer} style={{width: isExpand ? '200px' : '80px'}}>
            <div className={style.leftTopContainer}>
                <span className={style.title} onClick={toggleSize}
                      style={{width: isExpand ? '200px' : '80px'}}>{isExpand ? 'MTalk' : 'M'}</span>
                <Menu
                    mode="inline"
                    inlineCollapsed={!isExpand}
                    className={style.menuBox}
                    style={{width: isExpand ? '200px' : '80px'}}
                    theme={'dark'}
                    items={menuItems.map(item => ({
                        key: item.key,
                        icon: item.icon,
                        label: <Link to={item.path}>{item.label}</Link>
                    }))}
                />


            </div>

            <Button onClick={gotoHome} style={{
                width: '100%',
                backgroundColor: '#022134',
                color: '#fff',
                border: 'none'
            }}>{isExpand ? '<<<返回桌面' : '<<<'}</Button>
        </div>
    )
}


